package main

import (
	"log"
	"rbac-system/config"
	"rbac-system/database"
	"rbac-system/routes"

	"github.com/gin-gonic/gin"
)

func main() {
	// 初始化配置
	config.InitConfig()

	// 初始化数据库
	database.InitDB()

	// 自动迁移表结构和初始化数据
	database.AutoMigrate()
	database.InitData()

	// 设置Gin模式
	if config.AppConfig.Server.Mode == "release" {
		gin.SetMode(gin.ReleaseMode)
	} else {
		gin.SetMode(gin.DebugMode)
	}

	// 创建Gin实例
	router := gin.Default()

	// 设置CORS中间件
	router.Use(func(c *gin.Context) {
		c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
		c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	})

	// 设置路由
	routes.SetupRoutes(router)

	// 启动服务器
	port := config.AppConfig.Server.Port
	if port == "" {
		port = "8080"
	}

	log.Printf("RBAC权限管理系统启动成功，服务运行在 http://localhost:%s", port)
	log.Printf("健康检查地址: http://localhost:%s/health", port)

	if err := router.Run(":" + port); err != nil {
		log.Fatal("启动服务器失败:", err)
	}
}
